package org.jeecg.modules.ws.controller;

import java.io.File;
import java.util.Arrays;
import java.io.IOException;
import java.util.Date;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import cn.hutool.core.date.DateUtil;
import org.jeecg.common.api.vo.Result;
import org.jeecg.common.system.query.QueryGenerator;
import org.jeecg.common.aspect.annotation.AutoLog;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import lombok.extern.slf4j.Slf4j;
import org.jeecg.common.system.base.controller.JeecgController;
import org.jeecg.modules.ws.entity.WsCapitalDetail;
import org.jeecg.modules.ws.entity.WsCapitalInfo;
import org.jeecg.modules.ws.service.IWsCapitalDetailService;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.util.FileCopyUtils;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.servlet.ModelAndView;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.core.io.FileSystemResource;
import org.springframework.core.io.Resource;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;

/**
 * @Description: 资金支付详情
 * @Author: jeecg-boot
 * @Date:   2025-03-28
 * @Version: V1.0
 */
@Slf4j
@Api(tags="资金支付详情")
@RestController
@RequestMapping("/wsCapitalDetail")
public class WsCapitalDetailController extends JeecgController<WsCapitalDetail, IWsCapitalDetailService> {
	@Autowired
	private IWsCapitalDetailService WsCapitalDetailService;
	/**
	 * 本地：local minio：minio 阿里：alioss
	 */
	@Value(value="${jeecg.uploadType}")
	private String uploadType;

	@Value(value = "${jeecg.path.upload}")
	private String uploadpath;

	/**
	 * 分页列表查询
	 *
	 * @param wsCapitalDetail
	 * @param pageNo
	 * @param pageSize
	 * @param req
	 * @return
	 */
	@AutoLog(value = "资金支付详情-分页列表查询")
	@ApiOperation(value="资金支付详情-分页列表查询", notes="资金支付详情-分页列表查询")
	@GetMapping(value = "/list")
	public Result<?> queryPageList(WsCapitalDetail wsCapitalDetail,
								   @RequestParam(name="pageNo", defaultValue="1") Integer pageNo,
								   @RequestParam(name="pageSize", defaultValue="10") Integer pageSize,
								   HttpServletRequest req) {
		QueryWrapper<WsCapitalDetail> queryWrapper = QueryGenerator.initQueryWrapper(wsCapitalDetail, req.getParameterMap());
		Date xdsjStart = wsCapitalDetail.getXdsjStart();
		Date xdsjEnd = wsCapitalDetail.getXdsjEnd();
		Date payTimeStart = wsCapitalDetail.getPayTimeStart();
		Date payTimeEnd = wsCapitalDetail.getPayTimeEnd();
		if (xdsjStart != null && xdsjEnd != null){
			queryWrapper.lambda().ge(WsCapitalDetail::getXdsj,xdsjStart);
			queryWrapper.lambda().le(WsCapitalDetail::getXdsj,xdsjEnd);
		}
		if (payTimeStart != null && payTimeEnd != null){
			queryWrapper.lambda().ge(WsCapitalDetail::getPayTime,payTimeStart);
			queryWrapper.lambda().le(WsCapitalDetail::getPayTime,payTimeEnd);
		}
		queryWrapper.orderByDesc("pay_time");
		Page<WsCapitalDetail> page = new Page<WsCapitalDetail>(pageNo, pageSize);
		IPage<WsCapitalDetail> pageList = WsCapitalDetailService.page(page, queryWrapper);
		return Result.OK(pageList);
	}

	/**
	 * 添加
	 *
	 * @param wsCapitalDetail
	 * @return
	 */
	@AutoLog(value = "资金支付详情-添加")
	@ApiOperation(value="资金支付详情-添加", notes="资金支付详情-添加")
	@PostMapping(value = "/add")
	public Result<?> add(@RequestBody WsCapitalDetail wsCapitalDetail) {
		WsCapitalDetailService.save(wsCapitalDetail);
		return Result.OK("添加成功！");
	}

	/**
	 * 编辑
	 *
	 * @param wsCapitalDetail
	 * @return
	 */
	@AutoLog(value = "资金支付详情-编辑")
	@ApiOperation(value="资金支付详情-编辑", notes="资金支付详情-编辑")
	@PutMapping(value = "/edit")
	public Result<?> edit(@RequestBody WsCapitalDetail wsCapitalDetail) {
		WsCapitalDetailService.updateById(wsCapitalDetail);
		return Result.OK("编辑成功!");
	}

	/**
	 * 通过id删除
	 *
	 * @param id
	 * @return
	 */
	@AutoLog(value = "资金支付详情-通过id删除")
	@ApiOperation(value="资金支付详情-通过id删除", notes="资金支付详情-通过id删除")
	@DeleteMapping(value = "/delete")
	public Result<?> delete(@RequestParam(name="id",required=true) String id) {
		WsCapitalDetailService.removeById(id);
		return Result.OK("删除成功!");
	}

	/**
	 * 批量删除
	 *
	 * @param ids
	 * @return
	 */
	@AutoLog(value = "资金支付详情-批量删除")
	@ApiOperation(value="资金支付详情-批量删除", notes="资金支付详情-批量删除")
	@DeleteMapping(value = "/deleteBatch")
	public Result<?> deleteBatch(@RequestParam(name="ids",required=true) String ids) {
		this.WsCapitalDetailService.removeByIds(Arrays.asList(ids.split(",")));
		return Result.OK("批量删除成功！");
	}

	/**
	 * 通过id查询
	 *
	 * @param id
	 * @return
	 */
	@AutoLog(value = "资金支付详情-通过id查询")
	@ApiOperation(value="资金支付详情-通过id查询", notes="资金支付详情-通过id查询")
	@GetMapping(value = "/queryById")
	public Result<?> queryById(@RequestParam(name="id",required=true) String id) {
		WsCapitalDetail WsCapitalDetail = WsCapitalDetailService.getById(id);
		return Result.OK(WsCapitalDetail);
	}

	/**
	 * 导出excel
	 *
	 * @param request
	 * @param wsCapitalDetail
	 */
	@RequestMapping(value = "/exportXls")
	public ModelAndView exportXls(HttpServletRequest request, WsCapitalDetail wsCapitalDetail) {
		return super.exportXls(request, wsCapitalDetail, WsCapitalDetail.class, "资金支付详情");
	}

	/**
	 * 通过excel导入数据
	 *
	 * @param request
	 * @param response
	 * @return
	 */
	@RequestMapping(value = "/importExcel", method = RequestMethod.POST)
	public Result<?> importExcel(HttpServletRequest request, HttpServletResponse response) {
		return super.importExcel(request, response, WsCapitalDetail.class);
	}

	/**
	 * 文件上传
	 * @param mf
	 * @param id
	 * @return
	 */
	@PostMapping(value = "/upload")
	public Result<?> upload(MultipartFile mf,String id) {
		try {
			String fileName = null;
			File file = new File(uploadpath + "/" + id + File.separator);
			if (!file.exists()) {
				file.mkdirs();// 创建文件根目录
			}
			WsCapitalDetail detail = WsCapitalDetailService.getById(id);
			String orgName = mf.getOriginalFilename();
			String ext = ".txt";
			if (orgName != null && orgName.contains(".")) {
				ext = orgName.substring(orgName.indexOf("."));
			}
			fileName = DateUtil.formatDate(detail.getPayTime()) + detail.getPurpose() + detail.getXdje() + ext;
			String savePath = file.getPath() + File.separator + fileName;
			File savefile = new File(savePath);
			FileCopyUtils.copy(mf.getBytes(), savefile);
			String dbpath = fileName;
			if (dbpath.contains("\\")) {
				dbpath = dbpath.replace("\\", "/");
			}
			detail.setFilePath(savePath);
			WsCapitalDetailService.updateById(detail);
			return Result.OK(dbpath);
		} catch (IOException e) {
			log.error(e.getMessage(), e);
			return Result.error("文件上传失败");
		}
	}

	/**
	 * 文件下载
	 *
	 * @param id 文件ID
	 * @return 文件资源
	 */
	@AutoLog(value = "资金支付详情-文件下载")
	@ApiOperation(value="资金支付详情-文件下载", notes="资金支付详情-文件下载")
	@GetMapping(value = "/download")
	public ResponseEntity<Resource> download(@RequestParam(name="id", required=true) String id) {
		try {
			// 这里获取文件路径
			WsCapitalDetail detail = WsCapitalDetailService.getById(id);
			File file = new File(detail.getFilePath());
			if (!file.exists()) {
				return ResponseEntity.notFound().build();
			}
			Resource resource = new FileSystemResource(file);
			ResponseEntity<Resource> response = ResponseEntity.ok()
					.header(HttpHeaders.CONTENT_DISPOSITION, "attachment; filename=\"" + resource.getFilename() + "\"")
					.contentType(MediaType.APPLICATION_OCTET_STREAM)
					.body(resource);
			return response;
		} catch (Exception e) {
			log.error(e.getMessage(), e);
			return ResponseEntity.status(500).body(null);
		}
	}

	/**
	 * 通过excel导入数据
	 *
	 * @param file
	 * @return
	 */
	@RequestMapping(value = "/importTempExcel", method = RequestMethod.POST)
	public Result<?> importTempExcel(@RequestParam MultipartFile file) {
		return WsCapitalDetailService.importTempExcel(file);
	}
}
